/*
 * @Author: wwssaabb
 * @Date: 2021-11-23 10:45:03
 * @LastEditTime: 2021-12-18 15:41:39
 * @FilePath: \handwritten-code\demo\deepCopy.js
 */

//实现深拷贝

let loop = {}
loop.a = loop

let obj = [1, '2', {
    a: 3
  }, null, undefined, NaN, new Date(), Error('no Error'), /\[|\]/g,
  function () {}, () => {},
  Symbol(), loop
]

//方法1 JSON.stringify+JSON.parse
// let obj1 = JSON.parse(JSON.stringify(obj))
//console.log(obj1) //undefined会变为null、正则对象会变为{}、function和Symbol会变为null

//方法2 for in+递归、解决正则、Date、Error、Symbol、循环引用
function deepCopy(target) {
  if (typeof target !== 'object' || target === null) return target
  // if (typeof target === 'symbol') return Symbol.for(target.description)
  if (target instanceof RegExp) return target.constructor(target) //处理正则对象
  if (target instanceof Date) return new target.constructor(target.getTime()) //处理Date对象
  if (target instanceof Error) return new target.constructor(target.message) //处理Error对象
  let res = Array.isArray(target) ? [] : {}
  for (const k in target) {
    if (Object.hasOwnProperty.call(target, k)) {
      res[k] = deepCopy(target[k])
    }
  }
  return res
}
let obj2 = deepCopy(obj)
console.log(obj2)